package com.bx.implatform.ucc.interceptor;

import com.bx.implatform.config.SpringContextHolder;
import com.bx.implatform.session.SessionContext;
import com.bx.implatform.session.UserSession;
import com.bx.implatform.ucc.service.UccApiService;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.List;

public class UccHeaderInterceptor implements ClientHttpRequestInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;
    private final List<String> excludePaths; // 不拦截的路径列表

    private static final String UCC_TOKEN_KEY = "uccToken:";

    public UccHeaderInterceptor(RedisTemplate<String, Object> redisTemplate, List<String> excludePaths) {
        this.redisTemplate = redisTemplate;
        this.excludePaths = excludePaths;
    }
    private UccApiService getUccApiService() {
        return SpringContextHolder.getBean(UccApiService.class);
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        try {
            String requestUri = request.getURI().getPath();
            System.out.println("ucc拦截器拦截 = " + requestUri);
            // 检查当前请求是否在不拦截的路径中
            for (String excludePath : excludePaths) {
                if (requestUri.startsWith(excludePath)) {
                    return execution.execute(request, body); // 直接放行
                }
            }
            UserSession session = SessionContext.getSession();
            // 添加请求头
            HttpHeaders headers = request.getHeaders();
            // 系统登录地址
            if (requestUri.equals("/control/20140901/infs/login.json")) {
                String loginKey = session.getUserId() + ":" + "sxJK@2025";
                headers.add("Authorization", Base64.encodeBase64String(loginKey.getBytes()));
            } else {
                String uccToken = (String) redisTemplate.opsForValue().get(UCC_TOKEN_KEY + session.getUserId());
                if (uccToken == null) {
                    // 登陆融合通讯系统获取 token
                    getUccApiService().getUccToken();
                    uccToken = (String) redisTemplate.opsForValue().get(UCC_TOKEN_KEY + session.getUserId());
                    if(uccToken == null){
                        throw new RuntimeException("融合通讯用户过期");
                    }
                }
                headers.add("Authorization", uccToken);
            }
            return execution.execute(request, body);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}